package com.ecnu.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ecnu.common.core.controller.BaseController;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.utils.bean.BeanUtils;
import com.ecnu.system.domain.SysCommon;
import com.ecnu.system.domain.dto.BottomAddDTO;
import com.ecnu.system.domain.dto.BottomUpdateDTO;
import com.ecnu.system.domain.vo.BottomVo;
import com.ecnu.system.service.ISysCommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

import static com.ecnu.common.enums.CommonType.BOTTOM_MESSAGE;

@Api(tags = "底部信息栏")
@RestController
@RequestMapping("/information/bottom")
public class SysBottomController extends BaseController {

    @Autowired
    private ISysCommonService commonService;

    @ApiOperation(value = "新增底部信息栏")
    @PostMapping("/add")
    public AjaxResult addMessage(@RequestBody BottomAddDTO bottomAddDTO) {
        SysCommon bottom = new SysCommon();
        bottom.setType(BOTTOM_MESSAGE.getCode());
        bottom.setCreateBy(getUsername());
        BeanUtils.copyProperties(bottomAddDTO,bottom);
        boolean save = commonService.save(bottom);
        if (!save) {
            return error("新增失败");
        }
        return success("新增成功");
    }

    @ApiOperation(value = "修改底部信息栏")
    @PostMapping("/update")
    public AjaxResult updateBottom(@RequestBody BottomUpdateDTO bottomUpdateDTO) {
        SysCommon bottom = new SysCommon();
        bottom.setUpdateBy(getUsername());
        BeanUtils.copyProperties(bottomUpdateDTO,bottom);
        boolean update = commonService.updateById(bottom);
        if (!update) {
            return error("修改失败");
        }
        return success("修改成功");
    }

    @ApiOperation("查询底部信息栏")
    @GetMapping("message")
    public AjaxResult message() {
        List<SysCommon> list = commonService.list(new LambdaQueryWrapper<SysCommon>()
                .eq(SysCommon::getType, BOTTOM_MESSAGE.getCode())
                .orderByDesc(SysCommon::getCreateTime));
        if (list == null || list.isEmpty()) {
            return error("未找到对应的数据");
        }
        SysCommon first = list.stream().findFirst().get();
        BottomVo bottomVo = new BottomVo();
        BeanUtils.copyProperties(first, bottomVo);
        return success(bottomVo);
    }
}
